package au.edu.unsw.editingtool.web;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import au.edu.unsw.editingtool.db.DBLoginpool;
import au.edu.unsw.editingtool.global.EditingToolException;
import au.edu.unsw.editingtool.global.EditingToolGlobalConstant;

/**
 * Servlet Filter implementation class WebFilter
 */
public class WebFilter implements Filter {

    /**
     * Default constructor. 
     */
	
    public WebFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpSession session = ((HttpServletRequest)request).getSession(false); 
		DBLoginpool loginpool = new DBLoginpool();
		try {
		   if (!loginpool.checkValid((String) session.getAttribute(EditingToolGlobalConstant.sessionAttrUsername), 
								 	 session.getId(), 
								 	(String) session.getAttribute(EditingToolGlobalConstant.sessionAttrLid)))
			   returnError(response, "You are accessing the resource that you're not authorized to access.");
		   else 
			   chain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void returnError(ServletResponse response, String msg) throws IOException, ServletException {
		response.setContentType("text/html");
	    response.setCharacterEncoding("UTF-8");
		response.getWriter().println("<H1>Error: </H1>");
		response.getWriter().println("<h3>" + msg + "</h3>");
		response.flushBuffer();
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}
